package com.sjgtw.cloud.gateway.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sjgtw.cloud.common.core.constant.Constants;
import com.sjgtw.cloud.common.core.exception.CaptchaException;
import com.sjgtw.cloud.common.core.utils.IdUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.utils.sign.Base64;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.gateway.config.CaptchaConfig;
import com.sjgtw.cloud.gateway.service.IValidateCodeService;

/**
 * <p>Title: 验证码--服务层--实现</p>
 * <p>Description: </p>
 * @author Admin
 * @date 2021-4-9
 */
@Service
public class ValidateCodeServiceImpl implements IValidateCodeService
{
	@Autowired
	private RedisService redisService;

	/**
	 * 生成验证码
	 */
	@Override
	public AjaxResult createCapcha() throws IOException, CaptchaException {
		// 验证码 KEY
		String uuid = IdUtils.simpleUUID();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
		// 生成验证码
		String code = CaptchaConfig.generateVerifyCode(4);
		redisService.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
		// 生成图片
		int w = 111, h = 36;
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		CaptchaConfig.outputImage(w, h, stream, code);
		AjaxResult ajax = AjaxResult.success();
		ajax.put("uuid", uuid);
		ajax.put("img", Base64.encode(stream.toByteArray()));
		return ajax;
	}

	/**
	 * 校验验证码
	 */
	@Override
	public void checkCapcha(String code, String uuid) throws CaptchaException {
		if (StringUtils.isEmpty(code)) {
			throw new CaptchaException("验证码不能为空");
		}
		if (StringUtils.isEmpty(uuid)) {
			throw new CaptchaException("验证码已失效");
		}
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
		String captcha = redisService.getCacheObject(verifyKey);
		redisService.deleteObject(verifyKey);

		if (!code.equalsIgnoreCase(captcha)) {
			throw new CaptchaException("验证码错误");
		}
	}
}
